package com.msb.mall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.constant.OrderConstant;
import com.msb.common.dto.SeckillOrderDto;
import com.msb.common.exception.NoStockException;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;
import com.msb.common.utils.R;
import com.msb.common.vo.MemberVO;
import com.msb.mall.order.dao.OrderDao;
import com.msb.mall.order.entity.OrderEntity;
import com.msb.mall.order.entity.OrderItemEntity;
import com.msb.mall.order.entity.dto.OrderCreateDto;
import com.msb.mall.order.entity.vo.*;
import com.msb.mall.order.feign.CartFeignService;
import com.msb.mall.order.feign.MemberFeignService;
import com.msb.mall.order.feign.ProductFeignService;
import com.msb.mall.order.feign.WareFeignService;
import com.msb.mall.order.interceptor.AuthInterceptor;
import com.msb.mall.order.service.OrderItemService;
import com.msb.mall.order.service.OrderService;
import com.msb.mall.order.utils.OrderMsgProduct;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    OrderMsgProduct orderMsgProduct;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    OrderService orderService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    WareFeignService wareFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberVO memberVO = AuthInterceptor.threadLocal.get();
        //获取到RequestContextHolder相关信息
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() ->{
            //同步主线程的的RequestContextHolder
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1、查询当前登录用户对应的会员地址信息
            List<MemberAddressVo> address = memberFeignService.getAddress(memberVO.getId());
            orderConfirmVo.setAddress(address);
        },threadPoolExecutor);
        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() ->{
            //同步主线程的的RequestContextHolder
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //2、查询购物车选中的商品信息
            List<OrderItemVo> userCarItems = cartFeignService.getUserCarItems();
            orderConfirmVo.setItems(userCarItems);
        },threadPoolExecutor);
        CompletableFuture.allOf(future1,future2).get();
        //3、计算订单的总金额和需要支付的总金额 vo自动计算


        //4.生成防重复token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //token存储在redis中
        //order:token:用户编号
        stringRedisTemplate.opsForValue().set(OrderConstant.ORDER_TOKEN_PREFIX+":"+memberVO.getId(),token);
         orderConfirmVo.setOrderToken(token);
        return orderConfirmVo;
    }

    private final Lock lock = new ReentrantLock();

    /**
     * seata分布式事务 通过@GlobalTransactional
     * @param vo
     * @return
     * @throws NoStockException
     */
    @GlobalTransactional
    @Transactional()
    @Override
    public OrderResponseVo orderSubmit(OrderSubmitVo vo)  throws NoStockException{
        OrderResponseVo responseVo = new OrderResponseVo();
        //获取当前用户信息
        MemberVO memberVO = AuthInterceptor.threadLocal.get();
        //key
        String orderKey = OrderConstant.ORDER_TOKEN_PREFIX + ":" + memberVO.getId();
        String script = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        Long execute = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Collections.singletonList(orderKey),
                vo.getOrderToken());
        if(execute == 0){
            //表示验证失败，重复提交
            responseVo.setCode(1);
            return responseVo;
        }
        //创建订单
        OrderCreateDto orderCreateDto = createOrder(vo,memberVO);
        //保存订单
        saveOrder(orderCreateDto);
        responseVo.setOrderEntity(orderCreateDto.getOrderEntity());
        //锁定库存信息
        lockWareStock(orderCreateDto, responseVo);
        //同步更新用户积分
        //订单成功后需要给 消息中间件发送延迟30分钟的相关信息
        orderMsgProduct.sendOrderMessage(orderCreateDto.getOrderEntity().getOrderSn());
        //支付页面
        return responseVo;
    }

    /**
     * 支付宝支付信息封装数据
     * @param orderSn
     * @return
     */
    @Override
    public PayVO getOrderPay(String orderSn) {
        OrderEntity orderEntity = this.baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        PayVO payVO = new PayVO();
        payVO.setSubject(orderEntity.getOrderSn());
        payVO.setTotal_amount(orderEntity.getPayAmount().toString());
        payVO.setOut_trader_no(orderEntity.getOrderSn());
        payVO.setBody(orderEntity.getNote());
        return payVO;
    }


    @Override
    public void handleOrderComplete(String outTradeNo) {
        //更新订单状态
        this.baseMapper.updateOrderStatus(outTradeNo,OrderConstant.OrderStatusEnum.TO_SEND_GOODS.getCode());
        //TODO
        //更新库存数据量信息，库存数量递减

        //购物车中的支付商品移除

        //更新会员积分

    }

    /**
     * 快速完成订单的处理 秒杀活动
     * @param dto
     */
    @Transactional
    @Override
    public void quickCreateOrder(SeckillOrderDto dto) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(dto.getOrderSn());
        orderEntity.setStatus(OrderConstant.OrderStatusEnum.TO_SEND_GOODS.getCode());
        orderEntity.setTotalAmount(dto.getSeckillPrice());
        orderEntity.setPayAmount(dto.getSeckillPrice());
        orderEntity.setMemberId(dto.getMemberId());
        this.save(orderEntity);
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //TODO 根据skuId查询对应的sku信息和spu信息
        orderItemEntity.setOrderSn(dto.getOrderSn());
        orderItemEntity.setSkuPrice(dto.getSeckillPrice());
        orderItemEntity.setSkuId(dto.getSkuId());
        orderItemEntity.setRealAmount(dto.getSeckillPrice());
        orderItemEntity.setSkuQuantity(dto.getNum());
        orderItemService.save(orderItemEntity);
    }

    private void lockWareStock(OrderCreateDto orderCreateDto, OrderResponseVo responseVo) throws NoStockException{
        WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
        wareSkuLockVo.setOrderSn(orderCreateDto.getOrderEntity().getOrderSn());
        List<OrderItemVo> itemVos = orderCreateDto.getOrderItemEntity().stream().map(item -> {
            OrderItemVo itemVo = new OrderItemVo();
            itemVo.setSkuId(item.getSkuId());
            itemVo.setTitle(item.getSkuName());
            itemVo.setCount(item.getSkuQuantity());
            return itemVo;
        }).collect(Collectors.toList());
        wareSkuLockVo.setItems(itemVos);
        R lockStockResults = wareFeignService.orderLockStock(wareSkuLockVo);
        if(lockStockResults.getCode() == 0){
            //表示锁定库存成功
            responseVo.setCode(0);
        }else{
            //表示锁定库存失败
            responseVo.setCode(2);
            throw new NoStockException(1000L);
        }
    }

    /**
     *订单数据保存数据库
     */
    @Transactional
    public void saveOrder(OrderCreateDto orderCreateDto) {
        OrderEntity order =orderCreateDto.getOrderEntity();
        orderService.save(order);
        List<OrderItemEntity> orderItems = orderCreateDto.getOrderItemEntity().stream().peek(item -> item.setOrderId(order.getId())).collect(Collectors.toList());
        orderItemService.saveBatch(orderItems);

    }

    /**
     * 创建订单
     * @param vo
     * @return
     */
    private OrderCreateDto createOrder(OrderSubmitVo vo,MemberVO memberVO) {
        OrderCreateDto createDto = new OrderCreateDto();
        //创建orderEntity
        OrderEntity orderEntity = buildOrder(vo, memberVO);
        //创建OrderItemEntity
        List<OrderItemEntity>  items = buildOrderItems(vo,orderEntity.getOrderSn());
        //根据订单项计算订单总额
        BigDecimal total_amount = new BigDecimal(0);
        BigDecimal pay_amount = new BigDecimal(0);
        for (OrderItemEntity item :items) {
            total_amount = total_amount.add(item.getSkuPrice());
            pay_amount = pay_amount.add(item.getRealAmount());
        }
        //订单总额
        orderEntity.setTotalAmount(total_amount);
        //订单支付金额 折扣，优惠，积分后的支付金额，默认没有
        orderEntity.setPayAmount(pay_amount);

        createDto.setOrderEntity(orderEntity);
        createDto.setOrderItemEntity(items);
        return createDto;


    }

    private List<OrderItemEntity> buildOrderItems(OrderSubmitVo vo,String orderSn) {
        List<OrderItemEntity>  items = new ArrayList<>();
        //获取购物车商品信息，选中的
        List<OrderItemVo> userCarItems = cartFeignService.getUserCarItems();
        if(userCarItems != null && !userCarItems.isEmpty()){
            //同一查询skuId查询spu信息
            //远程调用商品服务
            List<OrderItemSpuInfoVo> spus = productFeignService.getOrderItemSpuBySpuId((Long[]) userCarItems.stream()
                    .map(OrderItemVo::getSpuId)
                    .distinct().toArray());
            Map<Long, OrderItemSpuInfoVo> collect = spus.stream().collect(Collectors.toMap(OrderItemSpuInfoVo::getId, item -> item));
            for (OrderItemVo itemVo :userCarItems) {
                OrderItemEntity  orderItemEntity =  buildOrderItem(itemVo, collect.get(itemVo.getSpuId()));
                orderItemEntity.setOrderSn(orderSn);
                items.add(orderItemEntity);
            }

        }
        return items;
    }

    /**
     * 根据一个购物车中的商品创建对应的 订单项
     * @param itemVo
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo itemVo,OrderItemSpuInfoVo spuInfoVo) {
        OrderItemEntity entity = new OrderItemEntity();
        entity.setSkuId(itemVo.getSkuId());
        entity.setSkuName(itemVo.getTitle());
        entity.setSkuPic(itemVo.getImage());
        entity.setSkuPrice(itemVo.getPrice());
        entity.setSkuQuantity(itemVo.getCount());
        String attr = StringUtils.collectionToDelimitedString(itemVo.getSkuAttr(), ";");
        entity.setSkuAttrsVals(attr);
        entity.setSkuId(itemVo.getSkuId());
        //spu信息
        entity.setSpuBrand(spuInfoVo.getBrandName());
        entity.setSpuName(spuInfoVo.getSpuName());
        entity.setSpuId(spuInfoVo.getId());
        entity.setSpuPic(spuInfoVo.getImg());
        //优惠卷信息
        //折扣金额
        entity.setPromotionAmount(new BigDecimal(0));
        //优惠金额
        entity.setCouponAmount(new BigDecimal(0));
        //积分抵扣金额
        entity.setIntegrationAmount(new BigDecimal(0));
        //商品总金额 总的数量*商品价格
        BigDecimal totalPrice = entity.getSkuPrice().multiply(new BigDecimal(entity.getSkuQuantity())).setScale(2, RoundingMode.UP);
        //优惠总金额
        BigDecimal total_amount = entity.getPromotionAmount().add(entity.getCouponAmount()).add(entity.getIntegrationAmount());
        //抵扣后的支付金额
        BigDecimal subtract = totalPrice.subtract(total_amount);
        entity.setRealAmount(subtract);
        //积分
        entity.setGiftGrowth(itemVo.getPrice().intValue());
        entity.setGiftIntegration(itemVo.getPrice().intValue());
        return entity;

    }

    private OrderEntity buildOrder(OrderSubmitVo vo, MemberVO memberVO) {
        OrderEntity orderEntity = new OrderEntity();
        //创建订单编号
        String orderSn = IdWorker.getTimeId();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setNote(vo.getNote());
        //设置会员信息
        orderEntity.setMemberId(memberVO.getId());
        orderEntity.setMemberUsername(memberVO.getUsername());
        //根据收货地址id 获取地址详细信息
        MemberAddressVo memberAddressVo = memberFeignService.getAddressById(vo.getAddrId());
        if(memberAddressVo != null ){
            orderEntity.setReceiverCity(memberAddressVo.getCity());
            orderEntity.setReceiverName(memberAddressVo.getName());
            orderEntity.setReceiverPhone(memberAddressVo.getPhone());
            orderEntity.setReceiverDetailAddress(memberAddressVo.getDetailAddress());
            orderEntity.setReceiverPostCode(memberAddressVo.getPostCode());
            orderEntity.setReceiverRegion(memberAddressVo.getRegion());
            orderEntity.setReceiverProvince(memberAddressVo.getProvince());
        }
        //订单总额

        //设置订单状态
        orderEntity.setStatus(OrderConstant.OrderStatusEnum.FOR_THE_PAYMENT.getCode());
        return orderEntity;
    }

}
